package com.cddx.logistics.service.impl;

import com.cddx.logistics.domain.dto.SysDictQueryDTO;
import com.cddx.logistics.domain.pojo.SysDict;
import com.cddx.logistics.domain.vo.SysDictItemVO;
import com.cddx.logistics.domain.vo.SysDictVO;
import com.cddx.logistics.mapper.SysDictItemMapper;
import com.cddx.logistics.mapper.SysDictMapper;
import com.cddx.logistics.service.SysDictService;
import com.cddx.logistics.util.model.Result;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

@Service
public class SysDictServiceImpl implements SysDictService {

    @Resource
    private SysDictMapper sysdictMapper;

    @Resource
    private SysDictItemMapper sysDictItemMapper;
    @Override
    public PageInfo<SysDictVO> queryPage(SysDictQueryDTO sysDictQueryDTO) {
        PageHelper.startPage(sysDictQueryDTO.getPage(),sysDictQueryDTO.getLimit());
        List<SysDictVO> sysdictVOList = sysdictMapper.queryPage(sysDictQueryDTO);
        PageInfo<SysDictVO> pageInfo = new PageInfo<>(sysdictVOList);
        return pageInfo;
    }



    @Override
    public boolean add(SysDict sysDict) {
        sysDict.setCreateTime(new Date());
        sysDict.setUpdateTime(new Date());
        return sysdictMapper.add(sysDict) > 0;
    }

    @Override
    public boolean update(SysDict sysDict) {
        sysDict.setUpdateTime(new Date());
        return sysdictMapper.update(sysDict) > 0;
    }

    @Override
    public Result delete(Integer id) {
        List<SysDictItemVO> items = sysDictItemMapper.queryByDictId(id);
        if (items != null && !items.isEmpty()) {
            return Result.error("删除失败，请先删除以下字典配置项", items);
        }
        boolean success = sysdictMapper.delete(id) > 0;
        return success ? Result.ok("删除成功") : Result.error("删除失败");
    }

    @Override
    public Result deleteBatch(List<Integer> ids) {
        List<Integer> failedIds = new ArrayList<>();
        List<SysDictItemVO> allItems = new ArrayList<>();

        for (Integer id : ids) {
            List<SysDictItemVO> items = sysDictItemMapper.queryByDictId(id);
            if (items != null && !items.isEmpty()) {
                failedIds.add(id);
                allItems.addAll(items);
            }
        }

        if (!failedIds.isEmpty()) {
            return Result.error("删除失败，请先删除以下字典配置项", allItems);
        }

        boolean success = sysdictMapper.deleteBatch(ids) > 0;
        return success ? Result.ok("批量删除成功") : Result.error("批量删除失败");
    }



}
